from src.database.connection import HospitalDatabase
import tkinter.messagebox

# Initialize database connection
db = HospitalDatabase()
if not db.connect():
    print("Failed to connect to database")
    exit()

class RoomBackend:
    """Backend logic for room management"""
    
    def __init__(self):
        self.db = db
    
    def add_room(self, room_data):
        """Add a new room to the database"""
        try:
            return self.db.add_room(
                room_number=room_data['room_number'],
                room_type=room_data['room_type'],
                capacity=room_data['capacity'],
                rate_per_day=room_data['rate_per_day'],
                floor_number=room_data.get('floor_number'),
                dept_id=room_data.get('dept_id')
            )
        except Exception as e:
            raise Exception(f"Error adding room: {str(e)}")
    
    def update_room(self, room_number, update_data):
        """Update room information"""
        try:
            return self.db.update_room(room_number, **update_data)
        except Exception as e:
            raise Exception(f"Error updating room: {str(e)}")
    
    def delete_room(self, room_number):
        """Delete a room from the database"""
        try:
            return self.db.delete_room(room_number)
        except Exception as e:
            raise Exception(f"Error deleting room: {str(e)}")
    
    def get_room(self, room_number):
        """Get room by number"""
        try:
            return self.db.get_room(room_number)
        except Exception as e:
            raise Exception(f"Error getting room: {str(e)}")
    
    def get_all_rooms(self):
        """Get all rooms from database"""
        try:
            return self.db.get_all_rooms()
        except Exception as e:
            raise Exception(f"Error getting all rooms: {str(e)}")
    
    def assign_room_to_patient(self, room_number, patient_id):
        """Assign a room to a patient"""
        try:
            return self.db.assign_room_to_patient(room_number, patient_id)
        except Exception as e:
            raise Exception(f"Error assigning room to patient: {str(e)}")
    
    def validate_room_data(self, room_data):
        """Validate room data before saving"""
        required_fields = ['room_number', 'room_type', 'capacity', 'rate_per_day']
        
        for field in required_fields:
            if not room_data.get(field):
                return False, f"Field '{field}' is required"
        
        # Validate capacity is positive integer (not float/decimal)
        try:
            capacity_str = str(room_data['capacity'])
            # Check if it contains decimal point
            if '.' in capacity_str:
                return False, "Capacity must be a whole number (integer), not a decimal"
            capacity = int(room_data['capacity'])
            if capacity <= 0:
                return False, "Capacity must be a positive integer"
        except ValueError:
            return False, "Capacity must be a valid integer"
        
        # Validate rate is positive
        try:
            rate = float(room_data['rate_per_day'])
            if rate <= 0:
                return False, "Rate per day must be a positive number"
        except ValueError:
            return False, "Rate per day must be a valid number"
        
        return True, "Valid"

